import './index.css'

import { Button, Col, Form, Input, Row, Space, message } from 'antd'
import React, { useState } from 'react'

import $axios from '@/sever'
import { useNavigate } from 'react-router-dom'

const layout = {
  labelCol: {
    span: 8
  },
  wrapperCol: {
    span: 16
  }
}
const tailLayout = {
  wrapperCol: {
    offset: 4,
    span: 16
  }
}

export default function Reset() {
  const navigate = useNavigate() // 路由跳转
  const [form] = Form.useForm()
  const [messageApi, contextHolder] = message.useMessage() //全局提示
  const [phone, setphone] = useState('')
  const [email, setemail] = useState('')
  const onFinish = async () => {
    const { code, msg, secret } = await $axios.post('/users/resetPwd', {
      phone: phone,
      email: email
    })
    if (code === 200) {
      sessionStorage.setItem('secret', secret)
      navigate('/resetpwd')
    } else {
      messageApi.open({
        type: 'error',
        content: msg
      })
      form.setFieldsValue({
        phone: ''
      })
    }
  }

  // 检查手机或邮箱
  const handlerCheck = (_, value) => {
    const regPhone = /1[356789]\d{9}/
    const repEmail = /^[1-9][0-9]{4,10}@qq\.com$/
    if (regPhone.test(value)) {
      setphone(value)
      return Promise.resolve()
    } else if (repEmail.test(value)) {
      setemail(value)
      return Promise.resolve()
    }
    return Promise.reject(new Error('手机或邮箱格式错误'))
  }
  return (
    <div className="reset">
      {contextHolder}
      <Row>
        <Col span={6} offset={6}>
          <p className="top-p">
            <img src="/login/password.svg" alt="" width="30" />
            查找用户
          </p>
        </Col>
      </Row>
      <Row>
        <Col span={6} offset={6} className="col">
          <h1>找到你的账号</h1>
          <p>输入你的QQ邮件地址或手机号码</p>
          <Form
            {...layout}
            form={form}
            name="control-hooks"
            onFinish={onFinish}
            style={{
              maxWidth: 600
            }}
          >
            <Form.Item
              validateFirst={true}
              name="phone"
              rules={[
                {
                  required: true
                },
                {
                  validator: handlerCheck
                }
              ]}
            >
              <Input style={{ borderRadius: 20 }} />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Space>
                <Button type="primary" htmlType="submit">
                  查询
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Col>
      </Row>
    </div>
  )
}
